<?php

function getDomain()
{
    return $_SERVER['SERVER_NAME'];
}

/**
 * 格式化输出函数
 *
 * @param mixed   $var
 * @param boolean $exit
 */
function pr($var,$exit = false)
{
    echo '<br/><pre style="font-size:14px;color:#22f;font-family:\'Courier New\'">';
    if (is_array($var)){
        print_r($var);
    }
    else if(is_object($var)){
        echo get_class($var)." Object";
    }
    else if(is_resource($var)){
        echo (string)$var;
    }
    else{
        echo var_dump($var);
    }
    echo '</pre><br/>';
    if ($exit) exit;
}


/**
 * 取$from~$to范围内的随机数
 * @param $from	下限
 * @param $to   上限
 * @return unknown_type
 */
function random_from_to($from,$to)
{
	$size = $from-$to;//数值区间
	$max  = 30000;//最大
	if($size < $max){
		return $from + mt_rand(0,$size);
	}
	else{
		if($size % $max){
			return $from + random_from_to(0,$size / $max) * $max + mt_rand(0,$size % $max);
		}
		else{
			return $from + random_from_to(0,$size / $max) * $max + mt_rand(0,$max);
		}
	}	
}


// 返回随机字符
function getRandomChars($chartype = 1, $length = 4) {
	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	switch ($chartype) {
		case 1:
			$s = 26;
			$e = 35;
			break;
		case 2:
			$s = 0;
			$e = 25;
			break;
		case 3:
			$s = 0;
			$e = 35;
			break;
	}
	$char = '';
	$i = 1;
	do {
		$char .= $chars{mt_rand($s, $e)};
		$i ++;
	}
	while ($i <= $length);
	return $char;
}


function add_slashes($string)
{
    if(!$GLOBALS['magic_quotes_gpc']) {
        if(is_array($string)) {
            foreach($string as $key => $val){
                $string[$key] = add_slashes($val);
            }
        }
        else{
            $string = addslashes($string);
        }
    }
    return $string;
}

if (!function_exists("htmlspecialchars_decode")) 
{
	function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT) {
	return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
	}
}


function CsubStr($str,$start,$end,$sss='...') 
{
    /*
    UTF-8 version of substr(), for people who can't use mb_substr() like me.
    Length is not the count of Bytes, but the count of UTF-8 Characters
    Author: Windix Feng
    Bug report to: windix(AT)263.net, http://www.douzi.org/blog
    - History -
    1.0 2004-02-01 Initial Version
    2.0 2004-02-01 Use PREG instead of STRCMP and cycles, SPEED UP!
    */
    preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $str, $ar);

    if(func_num_args() >= 3) {
        $end = func_get_arg(2);
        if(count($ar[0])>$end){
            $str = join("",array_slice($ar[0],$start,$end)).$sss;
        }
        else{
            $str = $str;
        }
    }
    else{
        $str = join("",array_slice($ar[0],$start)).$sss;
    }
    $patt = "/(<[^>]*\.\.\.)/";
    preg_match_all($patt, $str, $matches);
    $replace_str = $matches[1][0];
    $str = str_replace($replace_str, "...", $str);

    return $str;
}


function add_magic_quotes( $array ) {
	foreach ( (array) $array as $k => $v ) {
		if ( is_array( $v ) ) {
			$array[$k] = add_magic_quotes( $v );
		} else {
			$array[$k] = addslashes( $v );
		}
	}
	return $array;
}


function get_status_header_desc($code) {
	$code = abs(intval( $code ));
	$header_desc = array(
		100 => 'Continue',
		101 => 'Switching Protocols',
		102 => 'Processing',
		200 => 'OK',
		201 => 'Created',
		202 => 'Accepted',
		203 => 'Non-Authoritative Information',
		204 => 'No Content',
		205 => 'Reset Content',
		206 => 'Partial Content',
		207 => 'Multi-Status',
		226 => 'IM Used',		

		300 => 'Multiple Choices',
		301 => 'Moved Permanently',
		302 => 'Found',
		303 => 'See Other',
		304 => 'Not Modified',
		305 => 'Use Proxy',
		306 => 'Reserved',
		307 => 'Temporary Redirect',

		400 => 'Bad Request',
		401 => 'Unauthorized',
		402 => 'Payment Required',
		403 => 'Forbidden',
		404 => 'Not Found',
		405 => 'Method Not Allowed',
		406 => 'Not Acceptable',
		407 => 'Proxy Authentication Required',
		408 => 'Request Timeout',
		409 => 'Conflict',
		410 => 'Gone',
		411 => 'Length Required',
		412 => 'Precondition Failed',
		413 => 'Request Entity Too Large',
		414 => 'Request-URI Too Long',
		415 => 'Unsupported Media Type',
		416 => 'Requested Range Not Satisfiable',
		417 => 'Expectation Failed',
		422 => 'Unprocessable Entity',
		423 => 'Locked',
		424 => 'Failed Dependency',
		426 => 'Upgrade Required',

		500 => 'Internal Server Error',
		501 => 'Not Implemented',
		502 => 'Bad Gateway',
		503 => 'Service Unavailable',
		504 => 'Gateway Timeout',
		505 => 'HTTP Version Not Supported',
		506 => 'Variant Also Negotiates',
		507 => 'Insufficient Storage',
		510 => 'Not Extended'
		);
	return $header_desc;
}



/**
 * Make an akismet request
 * @param	array 	$args		Arguments to send to the akismet server
 * @param	string 	$host		Host to talk to
 * @param	array 	$url		URL to send to the host
 * @return 	mixed					False on error or the server response
 * @access	private
 */
function _akismet_send ( $args = "", $host = "", $url = "" ) {

	// All of these are mandatory
	if ( !( is_array( $args ) ) ) { return false; }
	if ( $host == "" )            { return false; }
	if ( $url  == "" )            { return false; }
	
	// The request we wish to send
	$content	= "";
	foreach ( $args as $key => $val ) {
		$content	.= "$key=" . rawurlencode( stripslashes( $val ) ) . "&";
	}

	// The actual HTTP request
	$request	= "POST $url HTTP/1.0\r\n"
		. "Host: $host\r\n"
		. "Content-Type: application/x-www-form-urlencoded\r\n"
		. "User-Agent: " . $GLOBALS["akismet_ua"] . " | vanhegan.net-akismet.inc.php/1.0\r\n"
		. "Content-Length: " . strlen( $content ) . "\r\n\r\n"
		. "$content\r\n";
		
	$port			= 80;
	$response	= "";
	
	// Open a TCP file handle to the server, send our data
	if ( false !== ( $fh = fsockopen( $host, $port, $errno, $errstr, 3 ) ) ) {
		fwrite( $fh, $request );
		while ( !( feof( $fh ) ) ) { $response	.= fgets( $fh, 1160 ); }
		fclose( $fh );	
		// Split header and footer
		$response	= explode( "\r\n\r\n", $response, 2 );
	}
	return $response[ 1 ];
}



// 禁止缓存
function noCache()
{
	setHeader("Pragma:no-cache\r\n");
	setHeader("Cache-Control:no-cache\r\n");
	setHeader("Expires:0\r\n");
}

// 生成javascript消息转向
function showMessage($message, $direction = '') {
	setHeader("Content-type: text/html; charset=utf-8\r\n");
	echo "<script type='text/javascript'>\n";
	foreach ((array) $message as $msg) echo "alert('$msg')\n";
	if ($direction) echo "window.location.href='$direction';";
	else echo "window.history.go(-1)";
	echo "</script>\n";
	exit;
}

// 生成javascript转向
function directUrl($direction) {
	setHeader("Content-type: text/html; charset=utf-8\r\n");
	echo "<script type='text/javascript'>\n";
	echo "window.location.href='$direction';";
	echo "</script>\n";
	exit;
}


// MD5加密密码
function encryptMd5($password) {
	$encryptkeys =  array(
		'0' => '!',
		'1' => '*',
		'3' => '%',
		'4' => '(',
		'5' => '#',
		'6' => ')',
		'7' => '+',
		'8' => '_',
		'9' => '&',
		'a' => '{',
		'c' => '}',
		'd' => 'D',
		'e' => '`',
		'g' => '"',
		'i' => '-',
		'k' => '=',
		'm' => ':',
		'n' => '<',
		'o' => ';',
		'p' => '>',
		'q' => ',',
		's' => '~',
		't' => ' ',
		'u' => 'U',
		'v' => 'V',
		'w' => ']',
		'y' => '?',
		'z' => '['
	);
	$encryptkeysFlip = array_flip($encryptkeys);
	for($i = 0; $i < strlen($password); $i ++) {
		if ($encryptkeys[$password{$i}]) {
			$password{$i} = $encryptkeys[$password{$i}];
		} 
		elseif ($encryptkeysFlip[$password{$i}]) {
			$password{$i} = $encryptkeysFlip[$password{$i}];
		}
	}
	return md5($password);
}




// 过滤HTML
function cHTML($HTML, $br = true) {
	$HTML = htmlspecialchars(trim($HTML));
	$HTML = str_replace("\t", ' ', $HTML);
	if ($br) {
		return nl2br($HTML);
	} else {
		return str_replace("\n", '', $HTML);
	}
}

// 获取IP
function getIP() {
	if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$ip = getenv('HTTP_CLIENT_IP');
	} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$ip = getenv('REMOTE_ADDR');
	} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	preg_match("/[\d\.]{7,15}/", $ip, $ipmatches);
	$ip = $ipmatches[0] ? $ipmatches[0] : 'unknown';
	unset($ipmatches);
	return $ip;
}


function _autoload($className)
{
    if (file_exists(CLASS_DIR . strtolower($className) . '.class.php')){
        require_once(CLASS_DIR. strtolower($className) . '.class.php');
    }
    else if (file_exists(CONTROLLER_DIR . strtolower($className) . '.class.php')){
        require_once(CONTROLLER_DIR . strtolower($className) . '.class.php');
    }
    else if (file_exists(MODEl_DIR . strtolower($className) . '.class.php')){
        require_once(MODEl_DIR . strtolower($className) . '.class.php');
    }
    else{
        /* Error Generation Code Here */
    }
}

//高亮关键字
function HighLight($Content,$KeyWords,$Num = '')
{
    $HighLightKeyWords = "<font color=red>$KeyWords</font>";
    $Content = str_replace($KeyWords,$HighLightKeyWords,$Content);
    if(!empty($Num)){
        $Content = CsubStr($Content,$Num);
    }
    return $Content;
}


/**
 * php DES解密函数
 *
 * @param string $key 密钥
 * @param string $encrypted 加密字符串
 * @return string
 */
function des_decode($key,$encrypted)
{
    $encrypted = base64_decode($encrypted);

    $td = mcrypt_module_open(MCRYPT_DES,'',MCRYPT_MODE_CBC,''); //使用MCRYPT_DES算法,cbc模式
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);

    mcrypt_generic_init($td, $key, $key);//初始处理
    $decrypted = mdecrypt_generic($td, $encrypted);//解密

    mcrypt_generic_deinit($td); //结束
    mcrypt_module_close($td);
    return   pkcs5_unpad($decrypted);
}
function pkcs5_unpad($text){
	$pad = ord($text{strlen($text)-1});
	if ($pad > strlen($text)) return $text;
	if (strspn($text, chr($pad),strlen($text) - $pad) != $pad) return $text;
	return substr($text, 0, -1 * $pad);
}
/**
 * php DES加密函数
 *
 * @param string $key 密钥
 * @param string $text 字符串
 * @return string
 */
function des_encode($key,$text){
    $y = pkcs5_pad($text);
    $td = mcrypt_module_open(MCRYPT_DES,'',MCRYPT_MODE_CBC,''); //使用MCRYPT_DES算法,cbc模式
    $ks = mcrypt_enc_get_key_size($td);

    mcrypt_generic_init($td, $key, $key);       //初始处理
    $encrypted = mcrypt_generic($td, $y);       //解密
    
    mcrypt_generic_deinit($td);       //结束
    mcrypt_module_close($td);
    return base64_encode($encrypted);
}
function pkcs5_pad($text,$block=8){
	$pad = $block - (strlen($text) % $block);
	return $text . str_repeat(chr($pad), $pad);
}




